<template>
  <div class="admin-layout">
    <AdminHeader />
    <div class="main-wrapper">
      <AdminNavbar />
      <div class="content-wrapper">
        <div class="process-parameter-container">
          <div class="page-header">
            <h2>设备参数记录管理</h2>
            <div class="header-actions">
              <el-input
                v-model="searchKeyword"
                placeholder="搜索设备名称"
                clearable
                class="search-input"
                @clear="handleSearch"
                @keyup.enter="handleSearch"
              >
                <template #suffix>
                  <el-icon class="el-input__icon" @click="handleSearch">
                    <Search />
                  </el-icon>
                </template>
              </el-input>
            </div>
          </div>

          <!-- 设备参数记录列表 -->
          <el-table :data="parameters" border style="width: 100%" v-loading="loading">
            <el-table-column prop="paramId" label="记录ID" width="80" />
            <el-table-column prop="equipmentId" label="设备号" width="180" />
              <el-table-column prop="orderId" label="订单号" width="180" />
              <el-table-column prop="taskId" label="所属工序号" width="180" />
            <el-table-column prop="type" label="参数所属工序" width="120" />
            <el-table-column label="记录时间" width="180">
              <template #default="scope">
                {{ formatDateTime(scope.row.recordTime) }}
              </template>
            </el-table-column>

              <el-table-column label="操作" width="450">
                  <template #default="scope">
                      <el-button size="small" type="info" @click="viewParamter(scope.row.paramValue)">查看参数</el-button>
                  </template>
              </el-table-column>
          </el-table>

          <!-- 分页 -->
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </div>
    </div>

      <!-- 设备详情查看对话框 -->
      <el-dialog
              v-model="detailDialogVisible"
              title="设备详情"
              width="600px"
      >
          <div v-if="detailDialogVisible" class="device-detail">
              <!-- 设备参数信息 -->
              <div v-if="tempParams.length > 0" class="device-params">
                  <h3>设备参数</h3>
                  <el-form label-position="left" label-width="120px">
                      <el-form-item v-for="(param, index) in tempParams" :key="index" :label="param.label">
                          <span>{{ param.value }}</span>
                      </el-form-item>
                  </el-form>
              </div>
              <div v-else class="no-params">
                  <el-empty description="暂无设备参数信息" />
              </div>
          </div>
          <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
          </template>
      </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import {
    getProcessParameters,
    getProcessParameterById,
    addProcessParameter,
    updateProcessParameter,
    deleteProcessParameter, getEquipmentById
} from '@/api/production'
import AdminHeader from '@/components/AdminHeader.vue'
import AdminNavbar from '@/components/AdminNavbar.vue'
import { Search, Plus, Edit, Delete, Warning } from '@element-plus/icons-vue'

// 数据定义
const parameters = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const searchKeyword = ref('')
const dialogVisible = ref(false)
const deleteDialogVisible = ref(false)
const isEdit = ref(false)
const currentParameter = ref(null)
const parameterFormRef = ref(null)


const tempParams = ref([]) // 用于存储解析后的设备参数
const detailDialogVisible = ref(false)


// 表单数据
const parameterForm = reactive({
  parameterId: null,
  equipmentId: null,
  equipmentName: '',
  parameterName: '',
  parameterValue: '',
  unit: '',
  recordTime: null,
  operator: '',
  remark: ''
})

// 表单验证规则
const rules = {
  equipmentId: [
    { required: true, message: '请输入设备ID', trigger: 'blur' },
    { type: 'number', message: '设备ID必须为数字', trigger: 'blur' }
  ],
  equipmentName: [
    { required: true, message: '请输入设备名称', trigger: 'blur' }
  ],
  parameterName: [
    { required: true, message: '请输入参数名称', trigger: 'blur' }
  ],
  parameterValue: [
    { required: true, message: '请输入参数值', trigger: 'blur' }
  ],
  operator: [
    { required: true, message: '请输入操作员姓名', trigger: 'blur' }
  ]
}
const viewParamter = async (row) => {
    try {

            // 解析pJson参数
            tempParams.value = []

            if (row) {
                try {
                    const pJsonObj = JSON.parse(row)
                    // 将JSON对象转换为表单项数组
                    Object.keys(pJsonObj).forEach(key => {
                        tempParams.value.push({
                            label: key,
                            value: pJsonObj[key],
                            key: key
                        })
                    })
                } catch (jsonError) {
                    console.error('解析pJson参数失败:', jsonError)
                    ElMessage.warning('设备参数格式不正确')
                }
            }

            detailDialogVisible.value = true
    } catch (error) {
        console.error('获取设备详情失败:', error)
        ElMessage.error('获取设备详情失败')
    }
}
// 获取设备参数记录列表
const fetchParameters = async () => {
  loading.value = true
  try {
    const params = {
      current: currentPage.value,
      size: pageSize.value
    }

    // 如果有搜索关键字，添加到参数中
    if (searchKeyword.value) {
      params.equipmentName = searchKeyword.value
    }

    const res = await getProcessParameters(params)
console.log(res)
    if (res.success) {
      parameters.value = res.data.records || res.data
      total.value = res.data.total || res.data.length
    } else {
      ElMessage.error(res.message || '获取设备参数记录失败')
    }
  } catch (error) {
    console.error('获取设备参数记录失败:', error)
    ElMessage.error('获取设备参数记录失败')
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  fetchParameters()
}

// 分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchParameters()
}

// 当前页变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchParameters()
}

// 打开添加对话框
const openAddDialog = () => {
  isEdit.value = false
  Object.assign(parameterForm, {
    parameterId: null,
    equipmentId: null,
    equipmentName: '',
    parameterName: '',
    parameterValue: '',
    unit: '',
    recordTime: new Date(),
    operator: '',
    remark: ''
  })
  dialogVisible.value = true
}

// 打开编辑对话框
const handleEdit = (row) => {
  isEdit.value = true
  Object.assign(parameterForm, {
    parameterId: row.parameterId,
    equipmentId: row.equipmentId,
    equipmentName: row.equipmentName,
    parameterName: row.parameterName,
    parameterValue: row.parameterValue,
    unit: row.unit,
    recordTime: row.recordTime ? new Date(row.recordTime) : new Date(),
    operator: row.operator,
    remark: row.remark || ''
  })
  dialogVisible.value = true
}

// 打开删除确认对话框
const handleDelete = (row) => {
  currentParameter.value = row
  deleteDialogVisible.value = true
}

// 确认删除
const confirmDelete = async () => {
  if (!currentParameter.value || !currentParameter.value.parameterId) return

  try {
    const res = await deleteProcessParameter(currentParameter.value.parameterId)

    if (res.success) {
      ElMessage.success(`参数记录已成功删除`)
      deleteDialogVisible.value = false
      await fetchParameters()
    } else {
      ElMessage.error(res.message || '删除参数记录失败')
    }
  } catch (error) {
    console.error('删除参数记录失败:', error)
    ElMessage.error('删除参数记录失败')
  }
}

// 提交表单
const submitForm = async () => {
  if (!parameterFormRef.value) return

  await parameterFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 设置记录时间
        if (!parameterForm.recordTime) {
          parameterForm.recordTime = new Date()
        }

        let res
        if (isEdit.value) {
          // 编辑记录
          res = await updateProcessParameter(parameterForm)
        } else {
          // 添加记录
          res = await addProcessParameter(parameterForm)
        }

        if (res.success) {
          const message = isEdit.value ? '编辑' : '添加'
          ElMessage.success(`参数记录${message}成功`)
          dialogVisible.value = false
          fetchParameters()
        } else {
          ElMessage.error(res.message || `参数记录${isEdit.value ? '编辑' : '添加'}失败`)
        }
      } catch (error) {
        console.error(`参数记录${isEdit.value ? '编辑' : '添加'}失败:`, error)
        ElMessage.error(`参数记录${isEdit.value ? '编辑' : '添加'}失败`)
      }
    }
  })
}

// 格式化日期时间
const formatDateTime = (datetime) => {
  if (!datetime) return ''
  return new Date(datetime).toLocaleString()
}

// 组件挂载时获取数据
onMounted(() => {
  fetchParameters()
})
</script>

<style scoped>
.admin-layout {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f7f9;
}

.main-wrapper {
  flex: 1;
  display: flex;
  overflow: hidden;
}

.content-wrapper {
  flex: 1;
  padding: 24px;
  overflow: auto;
  background: #fff;
  margin: 16px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.process-parameter-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-input {
  width: 250px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.delete-confirm {
  display: flex;
  align-items: center;
  gap: 10px;
}

.warning-icon {
  font-size: 24px;
  color: #F56C6C;
}
</style>
